package com.ck.express.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.ck.express.adapter.RecordAdapter
import com.ck.express.databinding.FragmentFailedRecordBinding
import com.ck.express.db.ExpressDatabase
import com.ck.express.db.dao.FailedDeliveryRepository
import com.ck.express.db.dao.FailedLatticeRepository
import com.ck.express.enums.RecordTypeEnum
import com.ck.express.vo.FailedRecord
import kotlinx.coroutines.launch

class OperationRecordFragment : Fragment() {

    private var _binding: FragmentFailedRecordBinding? = null
    private val binding get() = _binding!!

    private lateinit var recordType: RecordTypeEnum
    private lateinit var adapter: RecordAdapter
    private var allRecords: MutableList<FailedRecord> = mutableListOf()

    // 分页状态变量
    private var currentPage = 0
    private val pageSize = 20 // 每页加载20条
    private var isLoading = false
    private var isLastPage = false

    private val deliveryRepository by lazy {
        FailedDeliveryRepository(
            ExpressDatabase.getInstance(requireContext()).failedDeliveryRequestDao()
        )
    }

    private val latticeRepository by lazy {
        FailedLatticeRepository(
            ExpressDatabase.getInstance(requireContext()).failedLatticeRequestDao()
        )
    }

    companion object {
        fun newInstance(type: RecordTypeEnum): OperationRecordFragment {
            return OperationRecordFragment().apply {
                arguments = Bundle().apply {
                    putString("record_type", type.name)
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        recordType =
            RecordTypeEnum.valueOf(
                arguments?.getString("record_type") ?: RecordTypeEnum.DELIVERY.name
            )
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {
        _binding = FragmentFailedRecordBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setupRecyclerView()
        setupSearchView()
        setupSwipeRefresh()
        loadData(isRefresh = true) // 初始加载，刷新模式
    }

    private fun setupRecyclerView() {
        adapter = RecordAdapter { record ->
            //  handleRetry(record)
        }

        val layoutManager = LinearLayoutManager(requireContext())
        binding.recyclerView.layoutManager = layoutManager
        binding.recyclerView.adapter = adapter

        // 添加滚动监听实现下滑加载
        binding.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                val visibleItemCount = layoutManager.childCount
                val totalItemCount = layoutManager.itemCount
                val firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition()

                if (!isLoading && !isLastPage) {
                    // 当滚动到最后几个项目时加载下一页
                    if ((visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                        && firstVisibleItemPosition >= 0
                        && totalItemCount >= pageSize
                    ) {
                        loadData() // 加载下一页
                    }
                }
            }
        })
    }

    private fun setupSwipeRefresh() {
        binding.swipeRefresh.setOnRefreshListener {
            loadData(isRefresh = true) // 下拉刷新时，重置状态并加载第一页
        }
    }

    private fun setupSearchView() {
        binding.searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                filterRecords(query)
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                filterRecords(newText)
                return true
            }
        })
    }

    // 关键修改：支持分页加载
    private fun loadData(isRefresh: Boolean = false) {
        if (isLoading) return

        if (isRefresh) {
            // 刷新时重置状态
            currentPage = 0
            isLastPage = false
            allRecords.clear()
        } else if (isLastPage) {
            // 已经是最后一页，显示Toast提示
            Toast.makeText(requireContext(), "没有更多数据了", Toast.LENGTH_SHORT).show()
            return
        }

        isLoading = true
        binding.swipeRefresh.isRefreshing = true
        adapter.setLoading(true)

        viewLifecycleOwner.lifecycleScope.launch {
            try {
                val newRecords = when (recordType) {
                    RecordTypeEnum.DELIVERY -> {
                        deliveryRepository.getAllFailedRequests(currentPage, pageSize).map {
                            FailedRecord(
                                waybillNo = it.waybillNo,
                                createTime = it.createTime,
                                failureReason = it.failureReason ?: "未知原因",
                                retryCount = it.retryCount ?: 0,
                                recordType = RecordTypeEnum.DELIVERY.toString()
                            )
                        }
                    }

                    RecordTypeEnum.LATTICE -> {
                        latticeRepository.getAllFailedLatticeRequests(currentPage, pageSize).map {
                            FailedRecord(
                                waybillNo = it.waybillNo,
                                createTime = it.createTime,
                                failureReason = it.failureReason ?: "未知原因",
                                retryCount = it.retryCount ?: 0,
                                recordType = RecordTypeEnum.LATTICE.toString()
                            )
                        }
                    }
                }

                // 检查是否最后一页
                if (newRecords.size < pageSize) {
                    isLastPage = true
                }

                // 更新数据
                allRecords.addAll(newRecords)

                updateAdapter()
                currentPage++ // 成功加载后页码+1
            } catch (e: Exception) {
                // 错误处理
                binding.tvEmptyState.text = "数据加载失败: ${e.message}"
                binding.tvEmptyState.visibility =
                    if (allRecords.isEmpty()) View.VISIBLE else View.GONE
                Log.e("OperationRecord", "加载数据失败", e)
            } finally {
                isLoading = false
                binding.swipeRefresh.isRefreshing = false
                adapter.setLoading(false)
            }
        }
    }

    private fun filterRecords(query: String?) {
        val filtered = if (query.isNullOrEmpty()) {
            allRecords
        } else {
            Log.i("单号查询", "${query}")
            allRecords.filter {
                it.waybillNo.contains(query, ignoreCase = true) ||
                        it.failureReason.contains(query, ignoreCase = true)
            }
        }
        adapter.submitList(filtered)
        binding.tvEmptyState.visibility = if (filtered.isEmpty()) View.VISIBLE else View.GONE
    }

    private fun updateAdapter() {
        adapter.submitList(allRecords.toList())
        binding.tvEmptyState.visibility = if (allRecords.isEmpty()) View.VISIBLE else View.GONE
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}